package com.fast.admin.utils;

import com.fast.common.constant.RedisKeyConstant;
import com.fast.common.redis.RedisClient;
import com.fast.common.utils.SendMailCodeUtils;
import com.fast.common.utils.SendPhoneCodeUtils;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author fuhehuang
 * @email 2628279194@qq.com
 */

@NoArgsConstructor
@Component
public class SendCodeUtils {

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;// 发件人

    @Value("${jwt.token.expiration}")
    private int expiration;

    /**
     * 发送短信验证码
     *
     * @param phone
     * @param code
     * @return
     */
    @Async
    public Boolean sendCodeOfPhone(String phone, String code) {
        // 使用腾讯云发送短信
        SendPhoneCodeUtils.sendCode(code, phone);
        redisClient.set(RedisKeyConstant.CAPTCHA.concat(phone), code, expiration, TimeUnit.SECONDS);
        return true;
    }

    /**
     * 发送邮箱验证码
     *
     * @param mail
     * @param code
     * @return
     */
    @Async
    public void sendCodeOfMail(String mail, String code) {
        // 使用QQ发送验证码
        String content="<div>请输入该验证码:<br/>"+code+"</div>";
        SendMailCodeUtils.sendHtmlEmail(mailSender,from, "记账本验证码",content,mail);
        redisClient.set(RedisKeyConstant.CAPTCHA.concat(mail), code, expiration, TimeUnit.SECONDS);
    }

    //获取验证码
    public String getCode(String key) {
        return (String) redisClient.get(RedisKeyConstant.CAPTCHA.concat(key));
    }
}
